using System;
using System.Text;
using System.IO;
using OpenNETCF.Compression;

namespace zlibSampleCS
{
    class Program
    {
        static void Main(string[] args)
        {
            TestGZWriteStream();
            TestGZReadStream();
            TestCompressDecompress();

            TestInflateDeflate();
        }

        private static void TestCompressDecompress()
        {
            string source = "A quick brown fox jumped over lazy dogs";

            byte[] src = Encoding.ASCII.GetBytes(source);
            byte[] dst = new byte[1024];

            int compressedSize;

            ErrorCode ret = zlibCE.Compress(dst, src, out compressedSize);

            src = new byte[1024];
            int uncompressedSize;
            ret = zlibCE.Uncompress(src, dst, out uncompressedSize);
        }

        // Test deflate/inflate stream-to-stream (no headers, not a valid gzip file)
        private static void TestInflateDeflate()
        {
            string source = "A quick brown fox jumped over lazy dogs";

            StreamWriter wrt = new StreamWriter(@"\Storage Card\in.txt", false);
            for (int i = 0; i < 100; i++) wrt.WriteLine(source);
            wrt.Close();

            Stream inf = File.OpenRead(@"\Storage Card\in.txt");
            Stream outf = File.Create(@"\Storage Card\out.gz");

            zlibCE.Deflate(inf, outf, 9);

            inf.Close();
            outf.Close();

            inf = File.OpenRead(@"\Storage Card\out.gz");
            outf = File.Create(@"\Storage Card\out.txt");

            zlibCE.Inflate(inf, outf);
        }


        // Test deflating to stream
        private static void TestGZWriteStream()
        {
            GZStream stm = GZStream.OpenWrite(File.Create(@"\Storage Card\test.gz"), (CompressionLevel)5);
            string source = "A quick brown fox jumped over lazy dogs\r\n";


            for (int i = 0; i < 100; i++)
            {
                byte[] line = Encoding.ASCII.GetBytes(source);
                stm.Write(line, 0, line.Length);
            }
            stm.Close();
        }

        // Test inflating from gzipped file/stream (with the header)
        private static void TestGZReadStream()
        {
            GZStream stm = GZStream.OpenRead(File.OpenRead(@"\Storage Card\test.gz"));
            Stream stmOut = File.Create(@"\Storage card\test.txt");

            byte[] buf = new byte[8192];
            int cb = buf.Length;

            while ((cb = stm.Read(buf, 0, cb)) != 0)
            {
                stmOut.Write(buf, 0, cb);
                cb = buf.Length;
            }
            stm.Close();
            stmOut.Close();
        }
    }
}